from rest_framework.authentication import BasicAuthentication, TokenAuthentication
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.exceptions import ValidationError, NotFound
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response

from api.serializers.password_serializer import ForgetPasswordSerializer, ResetPasswordSerializer
from api.utils.sms.send_sms import validate_sms_code
from app.models import FMUser


@api_view(['PUT'])
def forget_password(request: Request):
    serializer = ForgetPasswordSerializer(data=request.data)
    if serializer.is_valid():
        username = serializer.validated_data['username']
        password = serializer.validated_data['password']
        sms_code = serializer.validated_data['sms_code']
        if not validate_sms_code(username, sms_code):
            raise ValidationError(u"验证码不正确或已失效")
        try:
            user = FMUser.objects.get(username=username)
            user.set_password(password)
            user.save()
        except FMUser.DoesNotExist:
            raise NotFound()
    else:
        raise ValidationError(serializer.errors)
    return Response({'detail': u'密码找回成功'})


@api_view(['PUT'])
@authentication_classes((BasicAuthentication, TokenAuthentication))
@permission_classes((IsAuthenticated, ))
def reset_password(request: Request):
    serializer = ResetPasswordSerializer(data=request.data)
    if serializer.is_valid():
        password = serializer.validated_data['password']
        sms_code = serializer.validated_data['sms_code']
        if not validate_sms_code(request.user.username, sms_code):
            raise ValidationError(u"验证码不正确或已失效")
        request.user.set_password(password)
        request.user.save()
    else:
        raise ValidationError(serializer.errors)
    return Response({'detail': u'密码修改成功'})
